package com.settlement.system.handler.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.settlement.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;

@Configuration
public class MQManager {

    @Bean()
    public RingBuffer<MessageVo> MessageVoRingBuffer() {
        //定义用于事件处理的线程池， Disruptor通过java.util.concurrent.ExecutorService提供的线程来触发consumer的事件处理
        //指定ringBuffer字节大小，必须为2的N次方（能将求模运算转为位运算提高效率），否则将影响效率
        int bufferSize = 1024 * 256;
        //单线程模式，获取额外的性能
        Disruptor<MessageVo> disruptor = new Disruptor<>(MessageVo::new, bufferSize, Executors.defaultThreadFactory());
        //设置事件业务处理器---消费者
        disruptor.handleEventsWith(new OrderConsumer());
        // 启动disruptor线程
        disruptor.start();
        //获取ringBuffer环，用于接取生产者生产的事件
        RingBuffer<MessageVo> ringBuffer = disruptor.getRingBuffer();
        return ringBuffer;
    }
}
